//
//  WBNetworkManager+Extension.swift
//  新浪微博
//
//  Created by 名品导购网MPLife.com on 2017/11/24.
//  Copyright © 2017年 sweet. All rights reserved.
//

import Foundation
//封装新浪微博的网络请求方法
extension WBNetworkManager{
    //加载微博数据字典数组
    //parameter completion :完成回调[list:微博字典数组/是否成功]
    //parameter since_id  返回ID比since_id大的微博 默认为0 即比since_id时间晚的微博
    //parameter max_id 返回ID小于或等于max_id的微博 默认为0
    func statusList(since_id:Int64,max_id:Int64,completion:@escaping (_ list:[[String:AnyObject]]?,_ isSuccess:Bool)->()) -> () {
        //加载微博数据
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //Swift中Int可以转换成AnyObject/但是Int64不行
        let params = ["since_id":"\(since_id)",
            "max_id":"\(max_id > 0 ? max_id-1 : 0)"
        ]
        tokenRequest(URLString: urlString, parameters: params as [String : AnyObject]) { (json, isSuccess) in
            //从json中获取status字典数组
            //如果as失败result == nil
            
            let result = json?["statuses"] as? [[String:AnyObject]]
            completion(result, isSuccess)
        }
    }
    //定时刷新的不需要提示是否失败
    func unreadCount(completion:@escaping (_ count:Int)->()) {
        
        guard let uid = userAccount.uid else {
            return
        }
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        let params = ["uid":uid]
        
        tokenRequest(URLString: urlString, parameters: params as [String : AnyObject]) { (json, isSuccess) in
            let dict = json as? [String:AnyObject]
            let count = dict?["status"] as? Int
            completion(count ?? 0)
        }
        
    }
}
//发布微博
extension WBNetworkManager{
    /// 发布微博
    ///
    /// - Parameters:
    ///   - text: 要发布的文本
    ///   - image: 要上传的图像 可以为nil  为nil 时就是发布纯文本微博
    ///   - completion: 完成回调
    func postStatuses(text:String,image:UIImage?,completion:@escaping (_ result:[String:AnyObject]?,_ isSuccess:Bool)->())->() {
        let urlStr:String
        //更具是否有图像 选择不同的URL
        if image == nil {
            urlStr = "https://api.weibo.com/2/statuses/update.json"
        }else{
            urlStr = ""
        }
        //参数字典
        let params = ["status":text]
        //如果图像不为空 需要设置name 和 data
        var name:String?
        var  data:Data?
        if image != nil {
            name = "pic"
            data = UIImagePNGRepresentation(image!)
        }
        //发起网络请求
        tokenRequest(method: .POST, URLString: urlStr, parameters: params as [String : AnyObject], name: name, data: data) { (json, isSuccess) in
            completion(json as? [String:AnyObject], isSuccess)
        }
    }
}


//用户信息
extension WBNetworkManager{
//  https://api.weibo.com/2/users/show.json

    func loadUserInfo(completion:@escaping (_ dict:[String:AnyObject])->()) {
        
        guard let uid = userAccount .uid else {
            return
        }
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = ["uid":uid]
        tokenRequest(URLString: urlString, parameters: params as [String : AnyObject]) { (json, isSuccess) in
            
            completion((json as? [String:AnyObject]) ?? [:])
        }
        
    }
}

extension WBNetworkManager {
    //加载token
    //授权码
    //完成回调 是否成功
    func loadAccessToken(code:String,completion:@escaping (_ isSuccess:Bool)->()) {
        let urlStrin = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id":WBAppKey,"client_secret":WBAppSecret,"grant_type":"authorization_code","code":code,"redirect_uri":WBRedirectUrl]
        //发起网络请求 没有需要token
        request(method: .POST, URLString: urlStrin, parameters: params as [String : AnyObject]) { (json, isSuccess) in
            //直接用字典设置UserAccount的属性
            //闭包里面用self
            //[:]空字典
            self .userAccount .yy_modelSet(with: (json as? [String:AnyObject]) ?? [:])
            //完成回调
            //如果请求失败，对用户账户数据不会有任何影响
            //加载当前用户信息
            self.loadUserInfo(completion: { (dict) in
//                print(dict)
                //使用用户信息字典 设置用户账户信息
                //昵称和头像地址
                self .userAccount .yy_modelSet(with: dict)
                self .userAccount .saveAccount()//保证用户名和头像也能被保存
                //加载用户信息加载完成再回调
                completion(isSuccess)
            })
        }
    }
}


